<template>
  <el-card shadow="never">
    <template #header>
      <el-form label-width="80px">
        <el-row :gutter="10">
          <el-col :span="6" :xs="24">
            <el-form-item label="角色名称">
              <el-input v-model="page.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label="状态">
              <el-select style="width: 100%;" v-model="page.status" clearable>
                <el-option :value="1" label="启用"></el-option>
                <el-option :value="0" label="禁用"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label-width="20px">
              <el-button type="primary" @click="getTableData">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <div style="margin-bottom: 10px;text-align: right">
      <el-button type="primary" icon="el-icon-plus" @click="addRole">添加角色</el-button>
    </div>
    <Table :tableColumn="tableColumn" :tableData="tableData" :page="page"
           @handleCurrentChange="(val)=>{page.pageNum = val,getTableData()}"
           @handleSizeChange="(val)=>{page.pageSize = val,getTableData()}"
    >
      <template #status="{row}">
        <el-switch :model-value="row.status === 1" @change="changeStatus(row)"></el-switch>
      </template>
      <template #handle="{row}">
        <el-button type="text" @click="editRole(row)">编辑</el-button>
      </template>
    </Table>
    <Dialog v-model="visible.isShow" :title="visible.title" @close="clearForm" @cancel="visible.isShow = false"
            @confirm="roleConfirm">
      <el-form label-width="80px" :model="roleForm" ref="formRef" :rules="roleRulesForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name"/>
        </el-form-item>
        <el-form-item label="权限配置">
          <el-tree
              ref="treeRef"
              :data="treeData"
              show-checkbox
              node-key="id"
              :props="{label:'name'}"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="roleForm.remark" :rows="5"></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
  </el-card>
</template>

<script>
import {defineComponent, reactive, toRefs, onMounted, ref, nextTick} from 'vue'
import {fetchPermission, fetchRoleList, fetchRoleType, increaseRole, updateRole, updateStatus} from '@/api/authority'
import {formatMenuTree} from '@/utils/index'
import {ElMessage} from "element-plus";

const tableColumn = [
  {label: '角色名称', align: 'center', prop: 'name', minWidth: 150},
  {label: '创建时间', align: 'center', prop: 'createTime', minWidth: 150},
  {label: '创建人', align: 'center', prop: 'inputName', minWidth: 100},
  {label: '备注', align: 'center', prop: 'remark', minWidth: 100},
  {label: '状态', align: 'center', slot: 'status', minWidth: 100},
  {label: '操作', align: 'center', slot: 'handle', minWidth: 100},
]
export default defineComponent({
  name: "RoleManage",
  setup() {
    const treeRef = ref(null)
    const formRef = ref(null)
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      treeData: [],
      tableData: [],
      visible: {
        isShow: false,
        type: 'add',
        title: '添加角色'
      },
      roleRulesForm: {
        name: [
          {required: true, message: '不能为空', trigger: 'blur'}
        ],
      },
      roleForm: {},
    })
    const methods = {
      async getTableData() {
        const res = await fetchRoleList(state.page)
        if (res.code === 200) {
          const {list, pageNum, pageSize, total} = res.data
          state.tableData = list
          state.page = {
            ...state.page,
            total
          }
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
        methods.getTableData()
      },
      async getPermission() {
        const res = await fetchPermission()
        if (res.code === 200) {
          state.treeData = formatMenuTree(res.data)
        }
      },
      addRole() {
        state.visible = {
          isShow: true,
          type: 'add',
          title: '添加角色'
        }
      },
      filterPid(list) {
        const data = list.filter(father => {
          const childArr = list.filter(child => father.id === child.parentId)
          if (childArr.length) {
            const isNodeCheck = childArr.some(check => !check.checked)
            if (isNodeCheck) {
              // 子节点有一个未勾选，去除父节点勾选
              father.checked = false
            }
          }
          return true
        })
        return {
          data
        }
      },
      async editRole({id, name, remark}) {
        state.roleForm = {
          id, name, remark
        }
        state.visible = {
          isShow: true,
          type: 'edit',
          title: '编辑角色'
        }
        const res = await fetchPermission({rid: id})
        if (res.code === 200) {
          nextTick(() => {
            // 去除父节点勾选
            const {data} = methods.filterPid(res.data)
            const keys = data.filter(item => item.checked)
            treeRef.value.setCheckedNodes(keys)
          })
        }
      },
      clearForm() {
        treeRef.value.setCheckedKeys([])
        state.roleForm = {}
        formRef.value.resetFields()
      },
      roleConfirm() {
        formRef.value.validate(async v => {
          if (v) {
            const treeKeys = [...treeRef.value.getCheckedKeys(), ...treeRef.value.getHalfCheckedKeys()]
            console.log(treeKeys)
            const {id, name, remark} = state.roleForm
            const api = ((params) => state.visible.type === 'add' ? increaseRole(params) : updateRole(params))
            const params = {
              name, remark
            }
            const rolePermissions = treeKeys.map(item => {
              return {
                pid: item,
              }
            })
            params.rolePermissions = rolePermissions
            if (id) params['rid'] = id
            const res = await api(params)
            if (res.code === 200) {
              ElMessage.success({
                message: state.visible.type === 'add' ? '添加成功' : '编辑成功'
              })
              state.visible.isShow = false
              methods.getTableData()
            }
          }
        })
      },
      async changeStatus({id, status}) {
        const res = await updateStatus({
          id,
          status: status === 1 ? 0 : 1
        })
        if (res.code === 200) {
          ElMessage.success({
            message: '操作成功'
          })
          methods.getTableData()
        }
      }
    }
    onMounted(() => {
      methods.getTableData()
      methods.getPermission()
    })
    return {
      tableColumn,
      ...toRefs(state),
      ...methods,
      treeRef,
      formRef
    }
  }
})
</script>

<style scoped>

</style>
